<script lang="ts">
	import { updateArchives } from '$gql/Mutations';
	import { archiveQuery } from '$gql/Queries';
	import { Direction, Layout, type FullArchiveFragment, type PageFragment } from '$gql/graphql';
	import { toastFinally } from '$lib/Toasts';
	import Guard from '$lib/components/Guard.svelte';
	import Head from '$lib/components/Head.svelte';
	import Titlebar from '$lib/components/Titlebar.svelte';
	import Grid from '$lib/containers/Grid.svelte';
	import Gallery from '$lib/gallery/Gallery.svelte';
	import PageView from '$lib/reader/PageView.svelte';
	import Reader, { initReaderContext } from '$lib/reader/Reader.svelte';
	import { initSelectionContext } from '$lib/selection/Selection.svelte';
	import ArchiveDelete from '$lib/tabs/ArchiveDelete.svelte';
	import ArchiveDetails from '$lib/tabs/ArchiveDetails.svelte';
	import ArchiveEdit from '$lib/tabs/ArchiveEdit.svelte';
	import Tab from '$lib/tabs/Tab.svelte';
	import Tabs from '$lib/tabs/Tabs.svelte';
	import { getContextClient } from '@urql/svelte';
	import type { PageProps } from './$types';

	let { data }: PageProps = $props();
	const client = getContextClient();
	const reader = initReaderContext();

	function updateCover(id: number) {
		updateArchives(client, { ids: data.id, input: { cover: { id } } }).catch(toastFinally);
	}

	let selection = initSelectionContext<PageFragment>(
		'Page',
		(p) => p.path,
		(p) => p.comicId === null
	);

	let result = $derived(archiveQuery(client, { id: data.id }));
	let archive: FullArchiveFragment | undefined = $state();

	$effect(() => {
		if (!$result.stale && $result.data?.archive.__typename === 'FullArchive') {
			archive = $result.data.archive;
			reader.pages = $result.data.archive.pages;
			selection.view = $result.data.archive.pages;
		}
	});
</script>

<Head section="Archive" title={archive?.name} />

{#if archive}
	<Grid>
		<header>
			<Titlebar title={archive.name} />
		</header>

		<aside>
			<Tabs>
				<Tab initial id="details" title="Details">
					<ArchiveDetails {archive} />
				</Tab>
				<Tab id="edit" title="Edit">
					<ArchiveEdit {archive} />
				</Tab>
				<Tab id="deletion" title="Delete">
					<ArchiveDelete {archive} />
				</Tab>
			</Tabs>
		</aside>

		<main class="overflow-auto">
			<Gallery pages={archive.pages} open={reader.open} {updateCover} />
		</main>
	</Grid>
{:else}
	<Guard {result} />
{/if}

<Reader>
	<PageView layout={Layout.Single} direction={Direction.LeftToRight} />
</Reader>
